
package linuxbox.download.servlet;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import java.sql.Timestamp;

import linuxbox.BoxStatic;
import linuxbox.util.*;
import linuxbox.common.*;
import linuxbox.download.logic.*;

/**
 * This servlet demonstrates one use of <tt>FileServlet</tt>.
 */
public class UploadAction extends Action {
	protected static String successJSP = null;
	
    public void doAction(HttpSession aSession, BoxSession aBoxSession, 
    HttpServletRequest req, HttpServletResponse res) throws Exception {
		BoxStatic.logger.debug("######### IN PROCESS FILE UPLOAD ##########");
        
		DownLoadObject dlo = (DownLoadObject)aSession.getAttribute(
			BoxStatic.DOWNLOAD_OBJECT);
		aSession.removeAttribute(BoxStatic.DOWNLOAD_OBJECT); 	        
		
		MultipartRequest multi = null;
		multi = new MultipartRequest(req, ".");
		String filename = "";
	
		// Get the list of files to be uploaded
		Enumeration files = multi.getFileNames();
	
		// Right now, we only support one file at a time
		if (files.hasMoreElements()) {
			// Get the name of the file
			String name = (String)files.nextElement();
	
			// Get the file system name of the file
			filename = multi.getFilesystemName(name);
			BoxStatic.logger.debug("FILENAME: " + filename);
	
			// Get File
			File f = multi.getFile(name);
	
			// Get content type of this file 
			String contentType = multi.getContentType(name);
	
			// create a byte array 
			FileInputStream inp = new FileInputStream(f);
			int FileLength = (int)f.length();
			byte[] cont = new byte[FileLength];
	
			// read from the input stream
			inp.read(cont);
	
			// call the processFile method
			processFile(filename, cont, contentType);
	
			// Close the input Stream
			inp.close();
		
			dlo.setFileName(filename);
			dlo.setFileSize(FileLength);
			dlo.setUploadDate(new Timestamp(System.currentTimeMillis()));
		
			DownLoadManager dm = DownLoadManager.getInstance();
			dm.addDownLoad(dlo);
		}

		redirectFile(successJSP, req, res);
	}

	public void setSuccessJSP(String str) {
		successJSP = str;
	}
	
	protected void processFile(String fileName, byte content[], 
	String contentType) throws Exception {
		BoxStatic.logger.debug("IN TestUpload Servlet " + contentType);

		BoxStatic.logger.debug("Before FOS");
		fileName = BoxStatic.HOME_DIR + BoxStatic.DOWNLOAD_FILE_DIR + fileName;
		//fileName = "/home/zhangjw/tomcat/webapps/linuxbox/download/test.jpg";
		FileOutputStream fos = new FileOutputStream(new File(fileName));
		fos.write(content);
		BoxStatic.logger.debug("After Write");
		fos.flush();
		fos.close();

		BoxStatic.logger.debug("Before return");
	}
}
